package com.wxy.网络编程;

import lombok.Locked;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class Server {
    public static void main(String[] args) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(20);
        //创建服务器
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);   //设置非阻塞
        //绑定服务器
        serverSocketChannel.bind(new InetSocketAddress(8888));
        //accept
        List<SocketChannel> channels = new ArrayList<>();
        while (true){
            //System.out.println("connecting");
            //建立连接，接收数据
            SocketChannel socketChannel = serverSocketChannel.accept(); //阻塞方法
            if(socketChannel != null){
                System.out.println(socketChannel + "connected");
                socketChannel.configureBlocking(false); //设置非阻塞
                channels.add(socketChannel);
            }

            for (SocketChannel c : channels){
                //System.out.println(c+"连接上了...");
                int readed = c.read(buffer); //阻塞方法
                if (readed > 0){
                    buffer.flip();
                    while (buffer.hasRemaining()){
                        System.out.print((char)buffer.get());
                    }
                    System.out.println("\t" + c);
                    buffer.clear();
                }
            }
        }
    }
}
